<template>
  <div>
    <el-table ref="table" :data="props.tableData"
              v-bind="{...otherDesc,...$attrs}"
              style="width: 100%" v-loading="props.loading"
              :class="{singleSelectTable:otherDesc.isSingleSelect}"
              @select="selectClick"
              @selection-change="tableSelection"
              @row-click="handleRowClick"
              @row-dblclick="handleRowDbClick">
      <template v-for="(item, index) in columns" :key="index">
        <template v-if="item.useSlot">
          <el-table-column v-bind="item">
            <template #default="scope">
              <slot :name="item.prop" :row="scope.row" />
            </template>
          </el-table-column>
        </template>
        <template v-else>
          <el-table-column v-bind="item"></el-table-column>
        </template>
      </template>
    </el-table>
  </div>
</template>

<script setup lang="ts">
import {nextTick, ref, unref} from "vue";
import { ElTable } from 'element-plus'

const props = defineProps({
  // 表格数据
  loading:{
    type:Boolean,
    default:false,
    required:true,
  },
  tableData:{
    type:Array,
    default:()=>[],
    required:true,
  },
  tableDesc:{
    type:Object,
    default:()=>({
      isSingleSelect:false,
      columns:[],
    }),
    required:true,
  },
})

const {columns,...otherDesc} = props.tableDesc

// 表格选择
const table = ref<InstanceType<typeof ElTable>>()
const selectArr = ref<any[]>([])
const emits = defineEmits(['changeSelect','rowClick','rowDbClick'])
const tableSelection = (val:any) => {
  selectArr.value = val;
  emits('changeSelect',unref(selectArr.value))
};
const selectClick = (selection:any, val:any) => {
  if (otherDesc.isSingleSelect){
    if (selection.length > 1) {
      let del_row = selection.shift();
      table.value?.toggleRowSelection(del_row, false);
    }
  }
}

const clearSelection = () => {
  table.value?.clearSelection();
}
const handleRowClick = (row:any) => {
  emits('rowClick',row)
  // 查找当前点击行在多选数组中的位置
  const selectIndex = selectArr.value.findIndex((item) => item.id == row.id);
  if (selectIndex == -1) {
    if(otherDesc.isSingleSelect){
      clearSelection()
      selectArr.value = [row];
    } else {
      selectArr.value.push(row);
    }
  } else {
    selectArr.value.splice(selectIndex, 1);
  }
  nextTick(() => {
    if (table.value) {
      table.value?.toggleRowSelection(row, selectIndex == -1);
    }
  });
};
const handleRowDbClick = (row:any) => {
  emits('rowDbClick',row)
}
defineExpose({
  table,
  clearSelection
})
</script>

<style scoped>
:deep(.singleSelectTable th.el-table__cell:nth-child(1) .cell) {
  visibility: hidden;
}
</style>
